package com.jingdianjichi.wx.handler;

import com.jingdianjichi.wx.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * ClassName :ReceiveTextMsgHandler
 * Package :com.jingdianjichi.wx.handler
 * Desciption :
 *
 * @Author :
 * @Create : 23:22
 * @Version :1.0
 */
@Component
@Slf4j
public class ReceiveTextMsgHandler implements WxChatMsgHandler {

    @Resource
    private RedisUtil redisUtil;

    private static final String LOGIN_PREFIX = "loginCode";

    @Override
    public WxChatMsgTypeEnum getMsgType() {
        return WxChatMsgTypeEnum.TEXT_MSG;
    }

    @Override
    public String dealMsg(Map<String, String> messageMap) {
        log.info("触发用户文本信息事件");
        String FromUserName = messageMap.get("FromUserName");
        String ToUserName = messageMap.get("ToUserName");
        String content = messageMap.get("Content");

        if (!"验证码".equals(content)) {
            return "";
        }

        Random random = new Random();
        int num = random.nextInt(10000);
        String numKey = redisUtil.buildKey(LOGIN_PREFIX, String.valueOf(num));
        redisUtil.setNx(numKey, FromUserName, 5L, TimeUnit.MINUTES);
        String numContent = "您当前的验证码是：" + num + "！ 5分钟内有效";
        String replayContent = "<xml>\n" +
                "  <ToUserName><![CDATA[" + FromUserName + "]]></ToUserName>\n" +
                "  <FromUserName><![CDATA[" + ToUserName + "]]></FromUserName>\n" +
                "  <CreateTime>12345678</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA[" + numContent + "]]></Content>\n" +
                "</xml>";
        return replayContent;

    }


}
